<?php
// +----------------------------------------------------------------------
// | OpenAdmin [ 基于ThinkPHP6和Vue3后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2022 OpenAdmin All rights reserved.
// +----------------------------------------------------------------------
// | Licensed (https://gitee.com/open_admin/OpenAdmin/blob/master/LICENSE)
// +----------------------------------------------------------------------
// | 作者: About 
// +----------------------------------------------------------------------
// | 修改时间:2022/8/22-16:35
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\middleware;

use app\common\model\system\MenuModel;

class CreateCrudMiddleware
{
    /**
     * Apidoc代码生成中间件
     * 生成文件及数据表前执行
     * 暂时无任何处理项
     * @param array $tplParams
     * @return array
     */
    public function before(array $tplParams): array
    {
        return $tplParams;
    }

    /**
     * 自动写入菜单数据和生成路由
     * 生成文件及数据表后执行
     * @param array $tplParams
     * @return void
     */
    public function after(array $tplParams): void
    {
        $crud               = [['action' => 'index', 'name' => '列表', 'methods' => 'GET'],
                               ['action' => 'add', 'name' => '添加', 'methods' => 'POST'],
                               ['action' => 'read', 'name' => '详情', 'methods' => 'GET'],
                               ['action' => 'edit', 'name' => '编辑', 'methods' => 'POST'],
                               ['action' => 'del', 'name' => '删除', 'methods' => 'POST']
        ];//默认要写入的几个方法
        $menu_pid           = $tplParams['form']['menu_id'];//前置已经做过必填处理
        $path               = $tplParams['controller']['path'] . '\\' . $tplParams['controller']['class_name'];
        $controller_layer   = \think\facade\Config::get('route.controller_layer', "controller") . '\\';//获取系统的控制器名称
        $substr             = substr(strstr($path, $controller_layer), strlen($controller_layer));//截取掉无用的部分
        $controller_prefix  = str_replace('\\', '.', $substr);//多级目录进行转换
        $path_array         = explode('\\', $path);//将完整路径解析为数组
        $after_route_prefix = strtolower($path_array[1] . '/' . str_replace('\\', '/', $substr));//路由前缀
        foreach ($crud as $v) {
            $menu_data['pid']         = $menu_pid;//上级菜单ID
            $menu_data['name']        = $tplParams['form']['controller_title'] . $v['name'];//菜单名称
            $menu_data['type']        = 2;//菜单类型默认为按钮
            $menu_data['mode']        = 1;//菜单模式默认为组件
            $menu_data['controller']  = $controller_prefix . '/' . $v['action'];//控制器真实路径
            $menu_data['after_route'] = $after_route_prefix . '/' . $v['action'];//控制器路由路径
            $menu_data['methods']     = $v['methods'];//控制器请求方法
            $all_data[]               = $menu_data;
        }
        (new MenuModel())->saveAll($all_data);
    }
}